package com.totoro.tygeneratedragonblock.executor.command.impl;

import com.totoro.tygeneratedragonblock.TyGenerateDragonBlock;
import com.totoro.tygeneratedragonblock.constants.StaticSystemVarConst;
import com.totoro.tygeneratedragonblock.executor.command.MainCommandExecutor;
import com.totoro.tygeneratedragonblock.pojo.SpawnPoint;
import com.totoro.tygeneratedragonblock.utils.ColorUtil;
import com.totoro.tygeneratedragonblock.utils.StrUtil;
import eu.decentsoftware.holograms.api.DHAPI;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.scheduler.BukkitRunnable;

import java.util.Map;

/**
 * @author Totoro
 * @version 0.1.0
 * @date 2025/8/10 - 18:41
 * @description
 **/
public class RemoveCommandExecutor implements MainCommandExecutor {
    @Override
    public void execute(TyGenerateDragonBlock plugin, CommandSender sender, String[] args) {
        if(!judgePermission(plugin, sender, null)) {
            return;
        }
        if(args.length != 2) {
            sender.sendMessage(plugin.getConfigManager().getConfig().getPrefix() + ColorUtil.color("&c用法: /tgdb remove <刷新点ID>"));
            return;
        }
        String spawnId = args[1];
        Map<String, SpawnPoint> spawnPoints = plugin.getSpawnersManager().getSpawnPoints();
        if(! spawnPoints.containsKey(spawnId)) {
            sender.sendMessage(plugin.getConfigManager().getConfig().getPrefix() + ColorUtil.color("&c该刷新点不存在"));
            return;
        }

        SpawnPoint spawn = spawnPoints.get(spawnId);

        // 移除位置映射
        plugin.getSpawnersManager().getLocationToSpawnId().remove(spawn.getLocation());

        // 取消重生任务
        BukkitRunnable task = plugin.getRespawnTasksManager().getRespawnTasks().remove(spawn.getLocation());
        if (task != null) {
            task.cancel();
        }

        // 移除方块（如果区块已加载）
        if (spawn.getLocation().getChunk().isLoaded()) {
            spawn.getLocation().getBlock().setType(Material.AIR);
        }

        // 如果加载了悬浮字依赖，尝试删除，因为config的配置可能修改，所以这里尝试删除悬浮字
        if (StaticSystemVarConst.dependentDecentHologramsEnable) {
            if(null != DHAPI.getHologram(StrUtil.toUniqueEnglish(spawn.getId()))) {
                DHAPI.removeHologram(StrUtil.toUniqueEnglish(spawn.getId()));
            }
        }

        // 删除配置文件和内存数据
        plugin.getSpawnersManager().removeSpawnersFile(spawnId);
        sender.sendMessage(plugin.getConfigManager().getConfig().getPrefix() + String.format(ColorUtil.color("&f已删除刷新点: &e[%s]"), spawnId));
    }
}
